package com.chagee.store.operation.server.utils;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @Author : hk
 * @Date : 2024/12/13
 */

@Slf4j
public class HttpRequestUtils {


	public static String doPost(String url, Map<String, String> headers, String body) {
		log.info("request:{}", body);
		String responseBody = "";
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			//创建httpclient对象
			HttpPost httpPost = new HttpPost(url);

			httpPost.setHeader("Content-Type", "application/json");
			// 添加请求头
			if (CollUtil.isNotEmpty(headers)) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpPost.addHeader(entry.getKey(), entry.getValue());
				}
			}
			StringEntity stringEntity = new StringEntity(body, "UTF-8");
			httpPost.setEntity(stringEntity);
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				responseBody = EntityUtils.toString(entity, "utf-8");
			}

			log.info("response:{}", responseBody);
		} catch (Exception e) {
			log.error("http doPost error:", e);
		}
		return responseBody;
	}

	public static String doGet(String url, Map<String, String> headers) {
		log.info("doGet_request:{}", url);
		//创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();

		String responseBody = "";
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("Content-Type", "application/json");
			// 添加请求头
			if (CollUtil.isNotEmpty(headers)) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpGet.addHeader(entry.getKey(), entry.getValue());
				}
			}
			response = client.execute(httpGet);

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				responseBody = EntityUtils.toString(entity, "utf-8");
			}

			log.info("doGet_response:{}", responseBody);
		} catch (Exception e) {
			log.error("http doGet error:", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseBody;
	}
}
